import os
import shutil
from pathlib import Path
import pandas as pd
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--species", required=True)
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()

# 数据所在路径
#dir = "/data/genome/IMP"
dir = args.input
#读取需要查找物种文件
with open(args.species,'r') as file:
    lines = [line.strip() for line in file if line.strip()]


#读取含有物种信息的文件
df = pd.read_csv('./20250814_cell_species.csv',header=0)
result_dict = {}
for _, row in df.iterrows():
    key = row.iloc[-1]
    value = (row.iloc[0], row.iloc[1])
    result_dict[key] = value
    

#print(lines)

#查找到物种相应文件后软链接到的目录
result_path = Path(args.output)

os.makedirs(result_path, exist_ok=True)


def safe_symlink_creation(source_file, target_dir):
    source_file = Path(source_file)
    file_name = source_file.name
    link_path = target_dir / f"{file_name}"
    try:
        link_path.symlink_to(source_file)
        print(f"成功创建软连接: {link_path} -> {protein_path}")
    except FileExistsError:
        print(f"错误：链接路径 '{link_path}' 已存在！")
    except OSError as e:
        print(f"创建链接失败: {e}")


prot_bed = []
bed_fasta = []

for species in lines:
    protein_path = f"{dir}/{species}/result/gff2protcds/{species}.prot.fasta"
    bed_path = f"{dir}/{species}/result/{species}.bed"
    cds_path = f"{dir}/{species}/result/gff2protcds/{species}.CDS.fasta"
    #protein_path_1 = f"{dir}/{species}/result1/gff2protcds/{species}.prot.fasta"
    
    #若文件存在，则链接到指定目录
    if os.path.exists(protein_path):
        id = result_dict[species][0]
        species_name = result_dict[species][1]
        fasta_file = f"/var/www/html/SynCoIV/public/data/system/prot/{species}.prot.fasta"
        gene_position = f"/var/www/html/SynCoIV/public/data/system/bed/{species}.bed"
        #print(f"{id},{species_name},prot,{fasta_file},{gene_position},system,0")
        prot_bed.append({
            'ID': id,
            'species': species_name,
            'species_shortname': species,
            'sequence_type': 'prot',
            'fasta_file': fasta_file,
            'gene_position_bed_file': gene_position,
            'source': 'system',
            'up_date':0
            })
        safe_symlink_creation(protein_path,result_path)
        
    else:
        print(f"未找到{species}蛋白序列文件")

    if os.path.exists(bed_path):
        safe_symlink_creation(bed_path,result_path)
        #pass
    else:
        print(f"未找到{species} bed文件")

    if os.path.exists(cds_path):
        id = result_dict[species][0]
        species_name = result_dict[species][1]
        fasta_file = f"/var/www/html/SynCoIV/public/data/system/CDS/{species}.CDS.fasta"
        gene_position = f"/var/www/html/SynCoIV/public/data/system/bed/{species}.bed"
        bed_fasta.append({
            'ID': id,
            'species': species_name,
            'species_shortname': species,
            'sequence_type': 'nucl',
            'fasta_file': fasta_file,
            'gene_position_bed_file': gene_position,
            'source': 'system',
            'up_date':0
            })

        safe_symlink_creation(cds_path,result_path)
    else:
        print(f"未找到{species} CDS文件")

# 两个文件输出
prot_bed_file = f"{result_path}/prot_bed_fasta_data.csv"
bed_fasta_file = f"{result_path}/bed_fasta_data.csv"
if prot_bed:
    df = pd.DataFrame(prot_bed)
    df.to_csv(prot_bed_file, index=False,quoting=1)

if bed_fasta:
    df = pd.DataFrame(bed_fasta)
    df.to_csv(bed_fasta_file, index=False,quoting=1)
